package com.drore.logapp.http;

import com.drore.logapp.http.interceptor.HttpInterceptor;
import com.drore.logapp.http.converter.GsonConverterFactory;
import com.drore.logapp.http.token.ProxyHandler;
import com.drore.logapp.utils.GlobalConfig;

import java.lang.reflect.Proxy;
import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;

/**
 * desc
 *
 * @author sixbing
 * @date 2018/12/11 11:52
 */
public class RetrofitTokenUtil {
    private static String TAG = "RetrofitTokenUtil";
    private static RetrofitTokenUtil instance, newInstance;
    private Retrofit retrofit;
    private OkHttpClient client;

    public static RetrofitTokenUtil getInstance() {
        if (instance == null)
            instance = new RetrofitTokenUtil(GlobalConfig.BASE_URL);
        return instance;
    }

    public static RetrofitTokenUtil getNewInstance() {
        if (newInstance == null)
            newInstance = new RetrofitTokenUtil(GlobalConfig.BASE_URL_new);
        return newInstance;
    }

    private RetrofitTokenUtil(String url) {
        client = new OkHttpClient.Builder()
                .addInterceptor(new HttpInterceptor())
                .readTimeout(10, TimeUnit.SECONDS)
                .writeTimeout(10, TimeUnit.SECONDS)
                .connectTimeout(10, TimeUnit.SECONDS)
                .build();
        retrofit = new Retrofit.Builder()
                .baseUrl(url)
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .client(client)  //设置网络请求，默认httpclient
                .build();
    }

    public HttpApi getHttpApi() {
        Class<HttpApi> tClass = HttpApi.class;
        HttpApi t = retrofit.create(tClass);
        return (HttpApi) Proxy.newProxyInstance(tClass.getClassLoader(), new Class<?>[]{tClass}, new ProxyHandler(t));
    }

    public <T> T getHttpApiMy(Class<T> tClass) {
        T t = retrofit.create(tClass);
        return (T) Proxy.newProxyInstance(tClass.getClassLoader(), new Class<?>[]{tClass}, new ProxyHandler(t));
    }
}
